package api

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"encoding/json"
)

type WechatUserInfo struct {
	WechatError

	Subscribe     int    `json:"subscribe"`
	OpenId        string `json:"openid"`
	Nickname      string `json:"nickname"`
	Sex           int    `json:"sex"`
	City          string `json:"city"`
	Country       string `json:"country"`
	Province      string `json:"province"`
	Language      string `json:"language"`
	Avatar        string `json:"headimgurl"`
	UnionId       string `json:"unionid"`
	SubscribeTime int64  `json:"subscribe_time"`
}

func RequestUserInfo(token, openId string) *WechatUserInfo {
	urlStr := "https://api.weixin.qq.com/cgi-bin/user/info" +
		"?access_token=" + token +
		"&openid=" + openId
	httpClient := &http.Client{}
	resp, err := httpClient.Get(urlStr)
	if err != nil || resp.StatusCode != http.StatusOK {
		fmt.Println("request userinfo error.", err, urlStr)
		return nil
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read userinfo error.", err, urlStr)
		return nil
	}

	info := &WechatUserInfo{}
	if err = json.Unmarshal(body, info); err != nil {
		fmt.Println("decode userinfo error.", err, urlStr, string(body))
		return nil
	} else if info.ErrCode != 0 {
		fmt.Println("the userinfo invalid.", urlStr, string(body))
		return nil
	}
	return info
}
